import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:imperius_insights/modules/guides/widgets/peddle_app.dart';
import 'package:imperius_insights/portal/env/environments.dart';
import 'package:imperius_insights/portal/state/mobx/widget-state.dart';
import 'package:imperius_insights/portal/widgets/error.dart';
import 'package:imperius_insights/portal/widgets/placeable_widget.dart';
import 'package:imperius_insights/portal/widgets/responsive-widget.dart';
import 'package:imperius_insights/routes/navigator.dart';
import 'package:imperius_insights/routes/paths.dart';
import 'package:imperius_insights/treaty/dimensions.dart';
import 'package:imperius_insights/treaty/palette.dart';
import 'package:imperius_insights/treaty/strings.dart';
import 'package:table_calendar/table_calendar.dart';

import 'view_model.dart';
import 'viewmodels/colors.dart';
import 'widgets/marked_projects.dart';
import 'widgets/project_item.dart';

class Screen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ScreenState();
  }
}

class ScreenState extends MobXWidgetState<Screen, ViewModel> {
  @override
  ViewModel createStore() {
    final scrollController = ScrollController();
    final vm = ViewModel();
    vm.setScrollController(scrollController);
    return vm;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: buildContent(context),
      floatingActionButton: ResponsiveWidget.isLandscape(context) ? null : FloatingActionButton(
          onPressed: () => navigateTo(context, Paths.projectsCalendar),
          child: Icon(Icons.date_range, size: 28,),
          tooltip: Strings.project_tasks_calendar,
          foregroundColor: Colors.white,
          backgroundColor: palette.theme),
    );
  }

  Widget buildContent(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      final isLandscape = ResponsiveWidget.isLandscape(context);
      final calendarArea = ConstrainedBox(
        constraints:
            BoxConstraints(maxWidth: isLandscape ? 300 : constraints.maxWidth),
        child: Observer(
          builder: (_) {
            return TableCalendar(
              onDaySelected: viewModel.onSelectCalendarDay,
              initialCalendarFormat:
                  isLandscape ? CalendarFormat.month : CalendarFormat.twoWeeks,
              headerStyle: HeaderStyle(
                  formatButtonVisible: false,
                  centerHeaderTitle: true,
                  decoration: BoxDecoration(color: palette.theme),
                  headerPadding: EdgeInsets.all(4),
                  headerMargin: EdgeInsets.only(bottom: 16),
                  titleTextStyle: TextStyle(
                      fontSize: fontDimensions.title, color: Colors.white),
                  leftChevronIcon:
                      Icon(Icons.arrow_back_ios, color: Colors.white),
                  rightChevronIcon:
                      Icon(Icons.arrow_forward_ios, color: Colors.white)),
              locale: 'zh_CN',
              calendarController: viewModel.calendarController,
              calendarStyle: CalendarStyle(
                markersPositionTop: 5,
                holidayStyle: TextStyle(color: Colors.green),
              ),
              builders:
                  CalendarBuilders(singleMarkerBuilder: (context, date, event) {
                final project = viewModel.queryByPMO(event);
                return Opacity(
                    opacity: 0.3,
                    child: Container(
                        width: 30,
                        height: 30,
                        margin: const EdgeInsets.symmetric(horizontal: 0.3),
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: stagingToColor(
                              project.calcMilestoneStaging(date)),
                        )));
              }),
              events: viewModel.calendarEvents,
            );
          },
        ),
      );
      final projectsArea = Expanded(
        child: RefreshIndicator(
          onRefresh: viewModel.refresh,
          color: palette.theme,
          child: PlaceableWidget(
            indicatorState: viewModel.projects,
            loadingWidgetBuilder: (context, indicator) {
              return Center(
                  child: SpinKitWave(
                      color: palette.theme,
                      size: layoutDimensions.indicatorSize));
            },
            errorWidgetBuilder: (_, indicatorState) {
              return NetworkErrorWidget(viewModel.refresh);
            },
            contentBuilder: (context, indicator) {
              return ListView.builder(
                controller: viewModel.scrollController,
                itemBuilder: (context, index) {
                  final project = viewModel.projects.data[index];
                  final double topPadding =
                      isLandscape ? (index == 0 ? 20 : 0) : 0;
                  return ProjectGlance(project,
                      onClicked: (p) => viewModel.onProjectTaped(project),
                      topPadding: topPadding,
                      showScheduledDatePoint: isWebRuntime,
                  );
                },
                padding: EdgeInsets.symmetric(horizontal: 20),
                itemCount: viewModel.projects.data.length,
              );
            },
          ),
        ),
      );
      return Container(
          color: palette.pageBackground,
          child: Column(
            children: <Widget>[
              isLandscape
                  ? Container()
                  : Container(
                      color: palette.theme,
                      padding: EdgeInsets.only(
                          top: MediaQuery.of(context).padding.top),
                    ),
              isWebRuntime ? PeddleBar() : Container(),
              Flexible(
                fit: FlexFit.loose,
                child: isLandscape
                    ? Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          projectsArea,
                          Container(
                            margin: EdgeInsets.all(20),
                            child: Material(
                              elevation: 8,
                              borderRadius: BorderRadius.circular(4),
                              shadowColor: Colors.grey,
                              color: Colors.white,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  calendarArea,
                                  SizedBox(height: 10),
                                  Divider(
                                      color: palette.divider,
                                      thickness: 0.5,
                                      height: 0),
                                  Observer(
                                    builder: (_) {
                                      return Text(
                                          viewModel.selectedDayTasksTitle,
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold));
                                    },
                                  ),
                                  Observer(
                                      builder: (_) => MarkedProjects(
                                          viewModel.markedProjects,
                                          viewModel
                                              .calendarController.selectedDay,
                                          viewModel.onTodoProjectTaped)),
                                ],
                              ),
                            ),
                          )
                        ],
                      )
                    : Column(
                        children: <Widget>[calendarArea, projectsArea],
                      ),
              )
            ],
          ));
    });
  }
}
